package com.jifen.common;

import com.jifen.constant.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class MyControllerAdvice {

    private Logger LOG = LoggerFactory.getLogger(MyControllerAdvice.class);

    /**
     * 全局异常捕捉处理
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception e) {
        e.printStackTrace();
        LOG.error("**服务器异常** " + e.getMessage());
        if(e instanceof DuplicateKeyException){
            return CommonResult.createErrorResult("请勿重复操作");
        }else if(e instanceof SerializationException){
            return CommonResult.createErrorResult(new MyException(ErrorCode.NOT_LOGIN));
        }
        return CommonResult.createErrorResult();
    }

    /**
     * 拦截捕捉自定义异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Result myErrorHandler(MyException e) {
        return CommonResult.createErrorResult(e);
    }
}
